/**
 *  字典表
 * 页面
 * @authors 汤露露
 * @date    2019-04-22
 * @version 0.1
 */
import { PlusOutlined } from '@ant-design/icons';
import { Input, Switch, Button, message, Popconfirm, Card } from 'antd';
import { useState, useRef } from 'react';
import { } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { connect } from 'umi';
// 详情页组件
import Description from '@/pages/common/description';
import ModalFormItem from './detail';
import { ProFormText } from '@ant-design/pro-form';
import Authorized from '@/components/Authorized';


// 用户列表
const SysDict = ({ dispatch, loading }: {

  dispatch: any;
  loading: boolean;
}) => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<any>();
  // tableList 数据源
  const [dataSource, setDataSource] = useState<{ data?: any[]; success?: boolean; total?: number; }>({ data: [], success: true, total: 0 });
  // 新增|编辑 窗口显示状态
  const [formModalVisible, handleModalVisible] = useState<boolean>(false);
  // 是否展示详情窗口
  const [showDetail, setShowDetail] = useState<boolean>(false);
  // 当前项的数据
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  // 是否是编辑
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const onChange = (record, checked) => {
    const state = checked ? 0 : 1;

    dispatch({
      type: 'sysDict/updateObject',
      payload: { id: record.id, state },
      callback: (response: any) => {
        if (response.code === 1) {
          message.success('操作成功');
          actionRef.current?.reload();
        } else {
          message.error(response.msg);
        }

      }
    });


  }
  const columns: ProColumns<API.RuleListItem>[] = [


    {
      title: '功能',
      dataIndex: 'name',
      editable: (text, record, index) => {
        return false;
      },
    },


    {
      title: '状态',
      dataIndex: 'state',

      editable: (text, record, index) => {
        return false;
      },
      render: (_, record) => {
        if (record.type == 0) {
          return <Authorized authority="sysDict:update"> <Switch checked={record.state != 1} onClick={(e) => { onChange(record, e) }} /></Authorized>
        } 
        return "";
        
      }

    },
    {
      title: '值',
      dataIndex: 'remark',
      editable: (text, record, index) => {
        if (record.type == 0) {
          return false;
        }

      },
    },

    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => {
        if (record.type === 1) {
          return <Authorized authority="sysDict:update"><a
            key="editable"
            onClick={() => {
              action?.startEditable?.(record.id);
            }}
          >
            编辑
          </a> </Authorized>


        }
      }

    },


  ];
  // 修改保存
  const saveRecord = (record: any) => {
    const hide = message.loading('修改中');
    dispatch({
      type: 'sysDict/updateObject',
      payload: { id: record.id, remark: record.remark },
      callback: (res: any) => {
        if (res.code === 1) {
          hide();
          message.success('修改成功');
          actionRef.current?.reload();

        } else {
          hide();
          message.error(res.msg);
          return false;
        }

      }
    });
  }

  // 列表查询
  const findPage = async (params: any) => {
    return new Promise((res, rej) => {
      dispatch({
        type: 'sysDict/findPage',
        payload: params,
        callback: (response: any) => {
          if (response.code === 1) {
            const { list: data, total } = response;
            res({ data, total, success: true });
          } else {
            rej();
          }

        }
      });
    });
  }

  return (
    <div>
        <ProTable
          options={false}
          headerTitle={''}
          actionRef={actionRef}
          rowKey="id"
          // search={{
          //   labelWidth: 120,
          // }}

          request={(params: any) => { return findPage(params) }}
          columns={columns}
          pagination={{ pageSize: 10 }}

          toolBarRender={false}
          search={false}

          editable={{
            // type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              saveRecord(data);
            },
            onChange: setEditableRowKeys,
            actionRender: (row, config, dom) => [dom.save, dom.cancel],
          }}
        />

        {/* 新增、编辑 */}
        <ModalFormItem
          isEdit={isEdit}
          currentRow={currentRow}
          formModalVisible={formModalVisible}
          handleModalVisible={(e: boolean) => {
            if (!e) {
              setIsEdit(e); // 修改为非编辑状态
              formRef?.current?.resetFields();// 情况表单上的值
            }
            handleModalVisible(e)
          }}
          setDataSource={(e: { data?: any[]; success?: boolean; total?: number; }) => setDataSource(e)}
          dataSource={dataSource}
          actionRef={actionRef}
          formRef={formRef}
          loading={loading}
        />

        {/* 详情查看 */}
        <Description
          showDetail={showDetail}
          setCurrentRow={(e: any) => setCurrentRow(e)}
          setShowDetail={(e: any) => setShowDetail(e)}
          currentRow={currentRow}
          columns={columns}
        />

      </div>
  );
};

export default connect(
  ({ loading }: { index: any; loading: any }) => ({

    loading: loading.models.sysDict,
  }),
)(SysDict);
